<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElTag } from 'element-plus'
import { Table } from '@/components/Table'
import {
  getTableListApi,
  saveTableApi,
  delTableListApi,
  initAppName,
  updateTableApi,
  putDriverApi
} from '@/api/data'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
const ids = ref<string[]>([])
initAppName('ExamLog')

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getTableListApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      mid: userStore.getUserInfo?.cid,
      ...unref(searchParams)
    })
    return {
      list: res.data.data.rows,
      total: res.data.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await delTableListApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { t } = useI18n()
const uploadData = ref(new FormData())
const uploadSectionFile = (param) => {
  console.log(param)
  //自定义文件上传
  const fileObj = param.file
  const fileName =
    param.data.sort + '_' + fileObj.name.split('.')[0] + '.' + fileObj.name.split('.')[1]
  uploadData.value.append('files', fileObj, fileName)
  console.log(uploadData.value.getAll('files'))
  uploadOcrData()
}
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles)
  // 创建一个新的 FormData 对象来存储筛选后的文件
  const newFormData = new FormData()

  // 遍历原始 FormData 对象中的所有文件
  for (const [key, value] of uploadData.value.entries()) {
    const na = value.name.split('_')[1]
    if (key === 'files' && na !== file.name.split('_')[0]) {
      // 如果文件名称不符合移除条件，则添加到新的 FormData 对象中

      newFormData.append(key, value)
    }
  }
  uploadData.value = newFormData
  console.log(uploadData.value.getAll('files'))
  // const it = uploadData.value.getAll('files').filter((item) => {
  //   return item.name !== file.name
  // })
}

const fileList1 = ref<[]>([
  // {
  //   name: 'food.jpeg',
  //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
  // }
])

const fileList2 = ref<[]>([
  // {
  //   name: 'food.jpeg',
  //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
  // }
])

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'id',
    label: t('tableDemo.index'),
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'trainContent',
    label: '培训内容',
    search: {
      component: 'Input'
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'trainSignIn',
    label: '签到表',
    search: {
      hidden: true
    },
    slots: {
      default: (data) => {
        return (
          <img
            style="max-width: 90%; height: auto;"
            src={data.row.trainSignIn ? data.row.trainSignIn.split(',')[0] : ''}
          />
        )
      }
    },
    form: {
      component: 'Upload',
      componentProps: {
        data: { sort: 'trainSignIn' },
        action: 'string',
        ref: 'uploadSun',
        fileList: fileList1,
        onRemove: handleRemove,
        // limit: 1,
        // onExceed: handleExceed,
        // autoUpload: false,
        httpRequest: uploadSectionFile
      }
    },
    detail: {
      span: 24,
      slots: {
        default: (data: any) => {
          return <img style="max-width: 90%; height: auto;" src={data.trainSignIn} fit="fit" />
        }
      }
    }
  },
  {
    field: 'trainImg',
    label: '培训照',
    search: {
      hidden: true
    },
    slots: {
      default: (data) => {
        return (
          <img
            style="max-width: 90%; height: auto;"
            src={data.row.trainImg ? data.row.trainImg.split(',')[0] : ''}
          />
        )
      }
    },
    form: {
      component: 'Upload',
      componentProps: {
        data: { sort: 'trainImg' },
        action: 'string',
        ref: 'uploadSun',
        fileList: fileList2,
        onRemove: handleRemove,
        // limit: 1,
        // onExceed: handleExceed,
        // autoUpload: false,
        httpRequest: uploadSectionFile
      }
    },
    detail: {
      span: 24,
      slots: {
        default: (data: any) => {
          return <img style="max-width: 90%; height: auto;" src={data.trainImg} fit="fit" />
        }
      }
    }
  },
  {
    field: 'trainDate',
    label: '培训日期',
    search: {
      hidden: true
    },
    form: {
      component: 'DatePicker',
      componentProps: {
        type: 'date',
        valueFormat: 'YYYY-MM-DD'
      }
    }
  },
  {
    field: 'content',
    label: t('exampleDemo.content'),
    search: {
      hidden: true
    },
    table: {
      show: false
    },
    form: {
      component: 'Editor',
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      slots: {
        default: (data: any) => {
          return <div innerHTML={data.content}></div>
        }
      }
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <BaseButton type="primary" onClick={() => action(data.row, 'edit')}>
                {t('exampleDemo.edit')}
              </BaseButton>
              <BaseButton type="success" onClick={() => action(data.row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              <BaseButton type="danger" onClick={() => delData(data.row)}>
                {t('exampleDemo.del')}
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<TableData | null>(null)
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = ''
  fileList1.value.length = 0
  fileList2.value.length = 0
}

const delLoading = ref(false)
const trainSignIn = ref([])
const trainImg = ref([])

const delData = async (row: TableData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: TableData, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  fileList1.value.length = 0
  fileList2.value.length = 0
  trainSignIn.value.length = 0
  trainImg.value.length = 0
  if (row.trainSignIn && row.trainSignIn != '') {
    row.trainSignIn.split(',').forEach((item) => {
      fileList1.value.push({ url: item })
    })
  }
  if (row.trainImg && row.trainImg != '') {
    row.trainImg.split(',').forEach((item) => {
      fileList2.value.push({ url: item })
    })
  }
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const uploadOcrData = async () => {
  const write = unref(writeRef)
  const uploadRes = await updateTableApi(uploadData.value)
  console.log(uploadRes.data.data)
  const imgArr = uploadRes.data.data
  trainSignIn.value.length = 0
  trainImg.value.length = 0
  imgArr.forEach((item: any) => {
    const type = item.split('/')[item.split('/').length - 1].split('_')[0]
    if (type === 'trainSignIn') {
      trainSignIn.value.push(item)
    } else if (type === 'trainImg') {
      trainImg.value.push(item)
    }
  })
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  const f1 = []
  const f2 = []
  fileList1.value.forEach((item) => {
    f1.push(item.url)
  })
  fileList2.value.forEach((item) => {
    f2.push(item.url)
  })
  const arr1 = [...f1, ...trainSignIn.value]
  const arr2 = [...f2, ...trainImg.value]
  formData.trainSignIn = arr1.join(',')
  formData.trainImg = arr2.join(',')

  if (formData) {
    let api = saveTableApi
    if (actionType.value === 'edit') {
      api = putTableApi
    }
    formData.mid = userStore.getUserInfo?.cid
    saveLoading.value = true
    const res = await api(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('exampleDemo.del') }}
      </BaseButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :image-preview="['image_uri']"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
<style>
.el-upload__input {
  display: block;
}
</style>
